<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <body>
    <div id="app">
      <div>提问：<input v-model="question" /></div>
      <div ref="answerEle" :data-question="question">{{ answer }}</div>
    </div>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <script>
      const { createApp, reactive, ref, watch } = Vue;

      function rand(min, max) {
        // [0, 1) * (max-min+1)
        // [0, max-min+1) 向下取整
        // [0, max-min]  + min
        // [min, max]
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }

      const app = createApp({
        setup() {
          const question = ref("");
          const answer = ref("");
          const answerEle = ref(null);

          let timeId;

          // 侦听一个 ref 响应式的变化
          watch(
            question,
            (newQuestion, oldQuestion) => {
              if (newQuestion.indexOf("?") > -1) {
                answer.value = "思考中...";
                console.log(answerEle.value.dataset.question);

                timeId && clearTimeout(timeId);
                timeId = setTimeout(() => {
                  answer.value = `结果为：${newQuestion}`;
                }, 1000);
              }
            },
            {
              // 指定 `flush: 'post'` 选项可访问的 DOM 将是被 Vue 更新之**后**的状态
              // 默认是 pre 表示之前
              // 这里的效果是：
              // flush: "post" -> 输出 "编程?" ， 多了个问号，表示最后一次DOM更新之后
              // flush: "pre" -> 仅输出 "编程" ， 少了个问好，表示最后一次DOM更新之前
              // 其他用法：watchPostEffect(callback) <=> watchEffect(callback, { flush: 'post' })
              flush: "post",
            }
          );

          return {
            question,
            answer,
            answerEle,
          };
        },
      });

      app.mount("#app");
    </script>
  </body>
</html>
